package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DeptFile;
import com.ruoyi.system.service.IDeptFileService;


/**
 * 部门文件Controller
 *
 * @author ruoyi
 * @date 2024-04-16
 */
@RestController
@RequestMapping("/system/dept/file")
public class DeptFileController extends BaseController
{
    @Autowired
    private IDeptFileService deptFileService;

    /**
     * 查询部门文件列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @PostMapping("/list")
    public AjaxResult list(@RequestBody DeptFile deptFile)
    {
        List<DeptFile> list = deptFileService.selectDeptFileList(deptFile);
        return success(list);
    }

    /**
     * 查询部门文件列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @GetMapping("/list/exclude/{fileId}")
    public AjaxResult excludeChild(@PathVariable(value = "fileId", required = false) Long fileId){
        List<DeptFile> deptFiles = deptFileService.selectDeptFileList(new DeptFile());
        deptFiles.removeIf(d -> d.getFileId().intValue() == fileId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), fileId + ""));
        return success(deptFiles);
    }

    /**
     * 获取部门文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId)
    {
        return success(deptFileService.selectDeptFileByFileId(fileId));
    }

    /**
     * 新建文件夹
     */
    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @Log(title = "部门文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody DeptFile deptFile)
    {
        if (!deptFileService.checkDeptFileNameUnique(deptFile))
        {
            return error("新增文件'" + deptFile.getFileName() + "'失败，文件名称已存在");
        }
        deptFile.setCreateBy(String.valueOf(getUserId()));
        deptFile.setCreateName(getUsername());
        return toAjax(deptFileService.insertDeptFile(deptFile));
    }

    /**
     * 上传
     */
    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @Log(title = "部门文件", businessType = BusinessType.INSERT)
    @PostMapping("/addFile")
    public AjaxResult addFile(@RequestBody DeptFile deptFile)
    {
        if (!deptFileService.checkDeptFileNameUnique(deptFile))
        {
            return error("新增文件'" + deptFile.getFileName() + "'失败，文件名称已存在");
        }
        deptFile.setCreateBy(String.valueOf(getUserId()));
        deptFile.setCreateName(getUsername());
        deptFileService.insertDeptFile(deptFile);
        return AjaxResult.success("添加成功");
    }


    /**
     * 移动到
     */
    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "部门文件", businessType = BusinessType.UPDATE)
    @PutMapping("/move")
    public AjaxResult move(@RequestBody DeptFile deptFileVo)
    {
        List<DeptFile> deptFileList = deptFileVo.getDeptFileList();
        for(DeptFile deptFile : deptFileList){
            Long fileId = deptFile.getFileId();
            if (!deptFileService.checkDeptFileNameUnique(deptFile))
            {
                return error("移动文件'" + deptFile.getFileName() + "'失败，文件名称已存在");
            }
            else if (deptFile.getParentId().equals(fileId))
            {
                return error("移动文件'" + deptFile.getFileName() + "'失败，上级文件不能是自己");
            }
            deptFile.setUpdateBy(String.valueOf(getUserId()));
        }
        return deptFileService.updateDeptFile(deptFileList);
    }

    /**
     * 复制到
     */
    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "部门文件", businessType = BusinessType.UPDATE)
    @PutMapping("/copy")
    public AjaxResult copy(@RequestBody DeptFile deptFileVo)
    {
        List<DeptFile> deptFileList = deptFileVo.getDeptFileList();
        for(DeptFile deptFile : deptFileList){
            Long fileId = deptFile.getFileId();
            if (!deptFileService.checkDeptFileNameUnique(deptFile))
            {
                return error("复制文件'" + deptFile.getFileName() + "'失败，文件名称已存在");
            }
            else if (deptFile.getParentId().equals(fileId))
            {
                return error("复制文件'" + deptFile.getFileName() + "'失败，上级文件不能是自己");
            }
            deptFile.setCreateBy(String.valueOf(getUserId()));
            deptFile.setCreateName(getUsername());
        }
        return deptFileService.copyDeptFile(deptFileList);
    }


    /**
     * 重命名
     */
    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "部门文件", businessType = BusinessType.UPDATE)
    @PutMapping("/rename")
    public AjaxResult edit(@RequestBody DeptFile deptFile)
    {
        if (!deptFileService.checkDeptFileNameUnique(deptFile))
        {
            return error("重命名'" + deptFile.getFileName() + "'失败，文件名称已存在");
        }
        return toAjax(deptFileService.updateDeptFileName(deptFile));
    }

    /**
     * 放入回收站/恢复文件
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "部门文件", businessType = BusinessType.DELETE)
    @PutMapping("/recycle")
    public AjaxResult recycleFile(@RequestBody DeptFile deptFile)
    {
        return toAjax(deptFileService.recycleDeptFile(deptFile));
    }

    /**
     * 收藏文件
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "部门文件", businessType = BusinessType.DELETE)
    @PostMapping("/storeFile")
    public AjaxResult storeFile(@RequestBody DeptFile deptFile)
    {
        deptFile.setUserId(getUserId());
        return deptFileService.storeDeptFile(deptFile);
    }

    /**
     * 下载
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "部门文件", businessType = BusinessType.DELETE)
    @PostMapping("/downloadFile")
    public AjaxResult downloadFile(@RequestBody DeptFile deptFile)
    {
        deptFile.setCreateBy(String.valueOf(getUserId()));
        deptFile.setCreateName(getUsername());
        return deptFileService.downloadFile(deptFile);
    }

    /**
     * 删除部门文件
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "部门文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fileId}")
    public AjaxResult remove(@PathVariable Long fileId)
    {
        return toAjax(deptFileService.deleteDeptFileByFileId(fileId));
    }

    /**
     * 根据ID查询所有子文件
     *
     * @param fileId 文件ID
     * @return 文件列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @Log(title = "部门文件", businessType = BusinessType.DELETE)
    @GetMapping("/selectChildren/{fileId}")
    public AjaxResult selectChildrenDeptFileByFileId(@PathVariable Long fileId){
        List<DeptFile> deptFiles = deptFileService.selectChildrenDeptFileByFileId(fileId);
        return success(deptFiles);
    }

}
